const router = require('koa-router')()

router.prefix('/routers')
const checkToken = require("../static/checkToken");
const getList = async (ctx) => {
    const { page } = ctx.request.body;
    const limit = 10; // Number of items per page
    const sql = "SELECT * FROM router ORDER BY router_id DESC";
    const result = await ctx.db.EXCUTE(sql, []);
    const start = (page - 1) * limit;
    const end = start + limit;
    const infoList = result.slice(start, end);
    return { infoList, length: result.length };
    }
const productId = () => {
    return Math.random().toString(36).substr(3) + Date.now().toString(36);
}

router.post('/getData', async(ctx, next) => {
    const isAuthenticated = await checkToken.cheakToken(ctx); // Check if user is authenticated
    if(isAuthenticated) {
    const { infoList, length } = await getList(ctx); // Get data from database
    ctx.body = { code: "200", msg: "成功获取数据", infoList, length };
    } else {
    ctx.body = { code: "500", msg: "验证没有通过" };
    }
    });
    router.post('/editData', async(ctx, next) => {
        const isAuthenticated = await checkToken.cheakToken(ctx);
        if(!isAuthenticated) {
        ctx.body = { code: "500", msg: "验证没有通过" };
        return;
        }
        
        const data = ctx.request.body;
        const existingRouteByName = await ctx.db.EXCUTE("select * from router where router_name = ?", [data.router_name]);
        const existingRouteById = await ctx.db.EXCUTE("select * from router where router_id = ?", [data.router_id]);
        
        if(existingRouteById.length === 0) {
          ctx.body = {code: "500", msg: `未找到 id 为 ${data.router_id} 的路线`};
          return;
        }
        
        if(existingRouteByName.length > 0 && existingRouteByName[0].router_id !== data.router_id) {
            ctx.body = {code: "500", msg: `路线名 "${data.router_name}" 已被占用，请重新输入`};
            return;
        }
        
        const updateSql = "update router set router_name = ?, router_way = ?, router_address = ?, router_phone = ? where router_id = ?";
        let result = await ctx.db.EXCUTE(updateSql, [data.router_name, data.router_way, data.router_address, data.router_phone, data.router_id]);
        let {infoList, length} = await getList(ctx);
        ctx.body = {code: "200", msg: "修改成功", infoList, length}
        });
router.post("/deleteData", async (ctx, next) => {
    let checkRes = await checkToken.cheakToken(ctx);
    if(checkRes) {
        let sql = "delete from router where router_id = ?"
        let result = await ctx.db.EXCUTE(sql, [ctx.request.body.router_id]);
        let {infoList, length} = await getList(ctx);
        ctx.body = {code: "200", msg: "成功删除", infoList, length};
    }else {
        ctx.body = {code: "500", msg: "验证没有通过"}
    }
})
router.post("/searchData", async (ctx, next) => {
    const isAuthenticated = await checkToken.cheakToken(ctx);
    if(!isAuthenticated) {
    ctx.body = {code: "500", msg: "验证没有通过"};
    return;
    }
    
    const { searchContent, page } = ctx.request.body;
    
    const sql = "select * from router where router_name like ?";
    const searchStr = `%${searchContent}%`;
    const result = await ctx.db.EXCUTE(sql, [searchStr]);
    
    const startIdx = (page - 1) * 10;
    const endIdx = page * 10;
    const infoList = result.slice(startIdx, endIdx);
    
    ctx.body = {code: "200", msg: "成功搜索", infoList, length: result.length};
    });
    router.post("/handleTop", async (ctx, next) => {
        const isAuthenticated = await checkToken.cheakToken(ctx);
        if (!isAuthenticated) {
        ctx.body = {code: "500", msg: "验证没有通过"};
        return;
        }
        
        const { router_id } = ctx.request.body;
        
        const fetchSql = "select * from router where router_id = ?";
        const deleteSql = "delete from router where router_id = ?";
        const insertSql = "insert into router (router_name, router_way, router_address, router_phone, router_id) values (?, ?, ?, ?, ?)";
        
        try {
            const result = await ctx.db.EXCUTE(fetchSql, [router_id]);
            if (result.length === 0) {
                ctx.body = {code: "404", msg: `路线 ${router_id} 不存在`};
                return;
            }
        
            await ctx.db.EXCUTE(deleteSql, [router_id]);
            await ctx.db.EXCUTE(insertSql, [result[0].router_name, result[0].router_way, result[0].router_address, result[0].router_phone, result[0].router_id]);
        
            const { infoList } = await getList(ctx);
            ctx.body = { code: "200", msg: "置顶成功", infoList };
        } catch (error) {
            console.error(error);
            ctx.body = {code: "500", msg: "置顶失败"};
        }
        });

module.exports = router